package com.jxit0573.android.lib.util;

import android.text.TextUtils;
import android.util.SparseArray;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @author jia
 */
public class CommonUtils {

    private CommonUtils() {
    }

    public static boolean isEmpty(List<?> list) {
        return list == null || list.isEmpty();
    }

    public static boolean isEmpty(Map<String, Object> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isEmpty(SparseArray<?> array) {
        return array == null || array.size() == 0;
    }

    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

    public static boolean isEmpty(CharSequence[] array) {
        return array == null || array.length == 0;
    }

    public static <T> T[] listToArray(String json, Class<T> clazz) {
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        List<T> list = JsonUtils.getList(json, clazz);
        if (isEmpty(list)) {
            return null;
        }
        try {
            T[] array = (T[]) Array.newInstance(clazz, list.size());
            return list.toArray(array);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static CharSequence[] listToArray(List<?> list, String key) {
        if (!isEmpty(list)) {
            CharSequence[] items = new CharSequence[list.size()];
            for (int i = 0; i < list.size(); i++) {
                Field[] fields = list.get(i).getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (key.equals(field.getName())) {
                        try {
                            items[i] = (CharSequence) field.get(list.get(i));
                            break;
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return items;
        } else {
            return null;
        }
    }
}
